package platform.boot.server;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Component("nettyServer")
public class NettyServer {

    // 配置服务端NIO线程组
    private final EventLoopGroup parent = new NioEventLoopGroup();
    private final EventLoopGroup child = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture bing(InetSocketAddress address){
        ChannelFuture channelFuture = null;
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(parent,child)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childHandler(new MyChannelInitializer());
            channelFuture = bootstrap.bind(address).syncUninterruptibly();
            channel = channelFuture.channel();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null != channelFuture && channelFuture.isSuccess()){
                System.out.println("启动成功");
            }else {
                System.out.println("启动失败");
            }
        }
        return channelFuture;
    }


    public void destroy(){
        if(null == channel)return;
        channel.close();
        parent.shutdownGracefully();
        child.shutdownGracefully();
    }

    public Channel getChannel(){
        return channel;
    }
}
